package com.lingshu.core.eventbus;

import org.greenrobot.eventbus.EventBus;

import java.util.Hashtable;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/4/12 9:34
 * @Description
 */
public class EventBusManager {
    /**
     * 保存黏性事件的EventBus对象
     * 解决默认 EventBus.getDefault() 连续发送黏性事件只有最后一个会生效
     */
    private static final Hashtable<EventKey, EventBus> customEventBusMap = new Hashtable<>();

    private static EventBus getDefaultEventBus() {
        return EventBus.getDefault();
    }

    private static EventBus getCustomEventBus() {
        return new EventBus();
    }

    /**
     * 黏性事件 {@link BaseStickySubscriber}
     * 普通事件 {@link BaseSubscriber}
     */
    public static <T> void register(BaseSubscriber<T> subscriber) {
        if (subscriber instanceof BaseStickySubscriber) {
            EventBus eventBus = getStickyEventBus(subscriber.key);
            if (!eventBus.isRegistered(subscriber)) {
                eventBus.register(subscriber);
            }
        } else {
            if (!getDefaultEventBus().isRegistered(subscriber))
                getDefaultEventBus().register(subscriber);
        }
    }

    /**
     * 取消注册
     */
    public static void unregister(BaseSubscriber<?> subscriber) {
        if (subscriber == null) return;
        if (subscriber instanceof BaseStickySubscriber) {
            EventBus eventBus = customEventBusMap.get(subscriber.key);
            if (eventBus != null) eventBus.unregister(subscriber);
        } else {
            getDefaultEventBus().unregister(subscriber);
        }
    }

    /**
     * 发送普通事件
     */
    public static <T> void post(EventData<T> eventData) {
        getDefaultEventBus().post(eventData);
    }

    /**
     * 发送黏性事件
     */
    public static <T> void postSticky(EventData<T> eventData) {
        getStickyEventBus(eventData.getKey()).postSticky(eventData);
    }

    private static EventBus getStickyEventBus(EventKey key) {
        EventBus eventBus = customEventBusMap.get(key);
        if (eventBus == null) {
            eventBus = getCustomEventBus();
            customEventBusMap.put(key, eventBus);
        }
        return eventBus;
    }
}
